import { useState, useMemo } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import "./index.css";

//模拟演唱会或电影院的座位：
// 1.座位状态：可选(available)、已售出(selected) 、已预定(booked)
// 50个座位
const seatData = Array.from({ length: 50 }, (_, index) => {
  return {
    id: `D${index + 1}`,
    status:
      index === 5 || index === 6 || index === 10 || index === 11
        ? "selected"
        : index % 3 === 0
        ? "booked"
        : "available",
  };
});

const Index = () => {
  const navigate = useNavigate();
  //获取详情页传递的参数
  const { state } = useLocation();
  const [seats, setSeats] = useState(seatData);
  const price = 140;

  //座位选择
  const handelSelItem = (id) => {
    setSeats((prev) => {
      //遍历座位数组，找到对应id的座位，切换状态
      return prev.map((item) => {
        //找到对应id的座位，并且不是已预定状态（已预定不能点击）
        if (item.id === id && item.status !== "booked") {
          return {
            ...item,
            status: item.status === "available" ? "selected" : "available",
          };
        }
        return item;
      });
    });
  };

  //筛选已选座位
  const selStates = useMemo(() => {
    return seats
      .filter((item) => item.status === "selected")
      .map((item) => item.id);
  }, [seats]);

  return (
    <div>
      {/* 座位布局 */}
      <div className="seatWrap">
        {seats.map((item, ind) => (
          <div
            className={`seat_item seat_item_${item.status}`}
            key={ind}
            onClick={() => handelSelItem(item.id)}
          >
            {item.status === "selected" && <span>{item.id}</span>}
          </div>
        ))}
      </div>
      {/* 图列布局 */}
      <div className="legend">
        <div className="legend-item">
          <span className="item-dot dot-available"></span> 可选 ¥{price}
        </div>
        <div className="legend-item">
          <span className="item-dot dot-booked"></span> 预选 ¥{price}
        </div>
        <div className="legend-item">
          <span className="item-dot dot-selected"></span> 已选 ¥{price}
        </div>
      </div>
      <div className="selSeats">
        <span>已选 {selStates.length}：</span>
        <p>{selStates.join("、")}</p>
      </div>
      <div className="allPrice">
        总价： <span>¥{(price * selStates.length).toFixed(2)}</span>
      </div>

      <div
        className="d_btn"
        onClick={() =>
          // navigate(
          //   `/order?seatcount=${selStates.length}&seatprice=${(
          //     price * selStates.length
          //   ).toFixed(2)}`,
          //   { state: state }
          // )
          navigate(`/order`, {
            state: {
              ...state,
              seatcount: selStates.length,
              seatprice: (price * selStates.length).toFixed(2),
            },
          })
        }
      >
        立即预定
      </div>
    </div>
  );
};

export default Index;
